package com.powernode.transaction;

import com.powernode.commons.util.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author Arrebol
 * @Date 2024/8/2 18:25
 * @Project jdbc
 * @Description：
 * 实现转账功能（不使用事务）
 * 实现某个完整的业务，通常是多条DML语句共同配合才能完成，
 * 我们有义务将这些DML语句捆绑在一起，这些语句要么都执行成功，要么都执行失败
 */
public class JdbcTest1 {
    public static void main(String[] args) {
        //转账金额
        double money = 10000;
        //实现转账功能
        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        try {
            conn = DbUtils.getConnection();
            String sql1 = "update t_act set balance = balance - ? where act_no = ?";
            ps1 = conn.prepareStatement(sql1);
            ps1.setDouble(1, money);
            ps1.setString(2, "act-001");
            int count1 = ps1.executeUpdate();
            System.out.println("execute："+sql1);
            System.out.println("count1 = " + count1);

            //模拟异常，再执行————少了10000块钱沃日
            //System.out.println(1/0);

            String sql2 = "update t_act set balance = balance + ? where act_no = ?";
            ps2 = conn.prepareStatement(sql2);
            ps2.setDouble(1,money);
            ps2.setString(2,"act-002");
            int count2 = ps2.executeUpdate();
            System.out.println("execute："+sql2);
            System.out.println("count2 = " + count2);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.close(null, ps1, null);
            DbUtils.close(null, ps2, null);
            DbUtils.close(null, null, conn);
        }
    }
}
